package com.zcurd.common.tool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.zcurd.common.util.StringUtil;
import com.zcurd.model.ZcurdField;
import com.zcurd.model.ZcurdHead;
import com.zcurd.model.ZcurdHeadBtn;
import com.zcurd.model.ZcurdHeadJs;
import com.zcurd.vo.ZcurdMeta;

/**
 * 
 * @author xpg
 *
 */

public class DbMetaTool {

	private static Map<Integer, ZcurdMeta> metaDataMap = new Hashtable<Integer, ZcurdMeta>();

	// 设置全局变量metaDataMap值
	public static ZcurdMeta getMetaData(int headId) {
		ZcurdMeta metaData = metaDataMap.get(headId);
		if (metaData == null) {
			metaData = getMetaDataFromDb(headId);
			metaDataMap.put(headId, metaData);
		}
		return metaData;
	}

	// 从数据库获取Head和field，btn,js信息，进行总体封装
	private static ZcurdMeta getMetaDataFromDb(int headId) {
		ZcurdHead head = ZcurdHead.me.findById(headId);
		List<ZcurdField> fieldList = ZcurdField.me.findByHeadId(head.get("id"));

		Map<String, Map<String, Object>> dictMap = new HashMap<String, Map<String, Object>>();
		for (ZcurdField zcurdField : fieldList) {
			String dictSql = zcurdField.getStr("dict_sql");
			if (StringUtil.isNotEmpty(dictSql)) {
				Map<String, Object> dictData = getDictData(dictSql);
				dictMap.put(zcurdField.getStr("field_name"), dictData);
				zcurdField.put("dict", dictData);
			}
		}
		// 添加表单字段列表
		List<ZcurdField> addFieldList = new ArrayList<ZcurdField>();
		// 更新表单字段列表
		List<ZcurdField> updateFieldList = new ArrayList<ZcurdField>();
		// 汇总等字段列表
		List<ZcurdField> footerFieldList = new ArrayList<ZcurdField>();
		// 如果是汇总字段，且显示在汇总列表
		for (ZcurdField zcurdField : fieldList) {
			if (zcurdField.getIsShowList() == 1 && zcurdField.getIsSum() == 1) {
				footerFieldList.add(zcurdField);
			}
			// 不是主键字段处理（主键不参与新增、更新操作）
			if (!zcurdField.getStr("field_name").equals(head.getStr("id_field"))) {
				if (zcurdField.getInt("is_allow_add") == 1) {
					addFieldList.add(zcurdField);
				}
				if (zcurdField.getInt("is_allow_update") == 1 || zcurdField.getInt("is_allow_detail") == 1) {
					updateFieldList.add(zcurdField);
				}
			}
		}
		List<ZcurdHeadBtn> btnList = ZcurdHeadBtn.me.findByHeadId(headId);
		List<ZcurdHeadBtn> topList = new ArrayList<ZcurdHeadBtn>();
		List<ZcurdHeadBtn> lineList = new ArrayList<ZcurdHeadBtn>();
		for (ZcurdHeadBtn btn : btnList) {
			if (btn.getInt("location") == 1) {
				topList.add(btn);
			} else if (btn.getInt("location") == 2) {
				lineList.add(btn);
			}
		}
		for (ZcurdHeadBtn btn : btnList) {
			if (btn.getInt("action") == 1) {
				head.set("form_type", 2); // 设置表单类型为主从
				break;
			}
		}
		List<ZcurdHeadJs> jsList = ZcurdHeadJs.me.findByHeadId(headId);

		ZcurdMeta zcurdMeta = new ZcurdMeta();
		zcurdMeta.setHead(head);
		zcurdMeta.setFieldList(fieldList);
		zcurdMeta.setDictMap(dictMap);
		zcurdMeta.setAddFieldList(addFieldList);
		zcurdMeta.setUpdateFieldList(updateFieldList);
		zcurdMeta.setFooterFieldList(footerFieldList);
		zcurdMeta.setBtnList(btnList);
		zcurdMeta.setTopList(topList);
		zcurdMeta.setLineList(lineList);
		zcurdMeta.setJsList(jsList);
		return zcurdMeta;
	}

	public static void updateMetaData(int headId) {
		metaDataMap.remove(headId);
	}

	/**
	 * dict_field表dict_sql 根据字典sql获得字典数据
	 */
	public static Map<String, Object> getDictData(String dictSql) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		// List<ZcurdDict> listDicts=new ArrayList<ZcurdDict>();
		List<Object> result = Db.query("select 'key','text' union all select * from (" + dictSql + ") a");
		Object[] dictList;
		String key;
		Object value;
		for (int j = 0; j < result.size(); j++) {
			dictList = (Object[]) result.get(j);
			key = dictList[0].toString();
			value = dictList[1];
			if (key.contains("key") || value.toString().contains("text")) {
				continue;
			}
			map.put(key, value);
		}
		// List<Record> listRecord = DBTool.use(dbSource).find("select
		// 'key','text' union all select * from (" + dictSql + ") a");
		// for (int i = 1; i < listRecord.size(); i++) {
		// Record record = listRecord.get(i);
		// map.put(record.getStr("key"), record.getStr("text"));
		// }
//		System.out.println("222222" + map);
		return map;
	}
	/**
	 * 重写方法。dict_field表dict_sql 根据字典sql获得字典数据
	 */
	public static Map<String, Object> getDictData(String dictSql,String dbSource) {
		/*// 解析dbSource，格式为[dbSource=xxx]select ...
//		String dbSource = "";
		if (dictSql.toLowerCase().startsWith("[dbSource".toLowerCase())) {
			dbSource = dictSql.substring(1, dictSql.indexOf("]")).split("=")[1].trim();
			dictSql = dictSql.substring(dictSql.indexOf("]") + 1);
		}*/

		Map<String, Object> map = new HashMap<String, Object>();
		// List<ZcurdDict> listDicts=new ArrayList<ZcurdDict>();
		List<Object> result = Db.query("select 'key','text' union all select * from (" + dictSql + ") a");
		Object[] dictList;
		String key;
		Object value;
		for (int j = 0; j < result.size(); j++) {
			dictList = (Object[]) result.get(j);
			key = dictList[0].toString();
			value = dictList[1];
			if (key.contains("key") || value.toString().contains("text")) {
				continue;
			}
			map.put(key, value);
		}
		// List<Record> listRecord = DBTool.use(dbSource).find("select
		// 'key','text' union all select * from (" + dictSql + ") a");
		// for (int i = 1; i < listRecord.size(); i++) {
		// Record record = listRecord.get(i);
		// map.put(record.getStr("key"), record.getStr("text"));
		// }
//		System.out.println("222222" + map);
		return map;
	}
	
}
